<template>
  <div>
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <main>
      <div class="title">
        <el-alert
          title="注意：只允许为第三级分类设置相关参数！"
          type="warning"
          show-icon
        >
        </el-alert>
        <div style="margin: 20px 0">
          <span>选择商品分类：</span>
          <el-cascader
            :value="value"
            :options="options"
            @change="handleChange"
          ></el-cascader>
        </div>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many"></el-tab-pane>
        <el-tab-pane label="静态属性" name="only"></el-tab-pane>
      </el-tabs>
      <div style="margin-bottom: 20px">
        <el-button type="primary" :disabled="isBtnDisabled" @click="addParams"
          >添加参数</el-button
        >
      </div>
      <el-table :data="listData" border style="width: 100%" :key="0">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div class="demo-table-expand">
              <el-tag
                :key="index"
                v-for="(tag,index) in scope.row.attr_vals.split(',')[0] === ''
                  ? []
                  : scope.row.attr_vals.split(',')"
                closable
                :disable-transitions="false"
                @close="handleClose(tag, scope.row)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @change="handleInputConfirm(scope.row)"
                @blur="scope.row.inputVisible=false"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >+ New Tag</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editParams(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteParams(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="修改静态属性" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <input type="hidden" name="attr_id" v-model="form.attr_id" />
          <el-form-item
            :label="activeName=='many'?'动态参数':'静态属性'"
            label-width="120px"
            :rules="[
              { required: true, message: activeName=='only'?'请输入静态属性':'请输入动态参数', trigger: 'blur' },
            ]"
          >
            <el-input v-model="form.attr_name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitParams">确 定</el-button>
        </div>
      </el-dialog>
    </main>
  </div>
</template>
<script>
import {
  getCategories,
  getGoodsAttribute,
  setGoodsAttribute,
  changeGoodsAttribute,
  deleteGoodsAttribute,
  addAttributes,
} from "@/api/goods";
export default {
  name: "ShopParams",
  data() {
    return {
      listData: [],
      list: [],
      value: [],
      options: [],
      activeName: "many",
      isBtnDisabled: true,
      dialogFormVisible: false,
      form: {},
    };
  },
  created() {
    this.getCategoriesList();
  },
  methods: {
    async deleteParams(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.form = JSON.parse(JSON.stringify(row));
          const res1 = await deleteGoodsAttribute({
            id: this.form.attr_id,
            attr_id: this.form.attr_id,
          });
          if (res1.data.meta.status !== 200) {
            this.$message.error("删除失败");
          } else {
            this.$message.success(res1.data.meta.msg);
            const res = await getGoodsAttribute({
              id: this.value[this.value.length - 1],
              sel: this.activeName,
            });
            this.listData = res.data.data;
            this.form = {};
            this.dialogFormVisible = false;
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async submitParams() {
      // console.log(this.form);
      if (this.form.attr_name === "") {
        return this.$message.error("请输入参数名称");
      }
      if (this.form.attr_id === "") {
        const res1 = await setGoodsAttribute({
          id: this.form.cat_id,
          attr_name: this.form.attr_name,
          attr_sel: this.form.attr_sel,
        });
        if (res1.data.meta.status !== 201) {
          this.$message.error("设置失败");
        } else {
          this.$message.success(res1.data.meta.msg);
          const res = await getGoodsAttribute({
            id: this.value[this.value.length - 1],
            sel: this.activeName,
          });
          res.data.data.forEach((item) => {
            // item.tag = {
            //   dynamicTags: ["标签一"],
            //   inputVisible: false,
            //   inputValue: "",
            // };
            item.inputVisible = false;
            item.inputValue = "";
          });
          this.listData = res.data.data;
          this.form = {};
          this.dialogFormVisible = false;
        }
      } else {
        const res1 = await changeGoodsAttribute({
          id: this.form.cat_id,
          attr_name: this.form.attr_name,
          attr_sel: this.form.attr_sel,
          attr_id: this.form.attr_id,
        });
        // console.log(res);
        if (res1.data.meta.status !== 200) {
          this.$message.error("设置失败");
        } else {
          this.$message.success(res1.data.meta.msg);
          const res = await getGoodsAttribute({
            id: this.value[this.value.length - 1],
            sel: this.activeName,
          });
          res.data.data.forEach((item) => {
            // item.tag = {
            //   dynamicTags: ["标签一"],
            //   inputVisible: false,
            //   inputValue: "",
            // };
            item.inputVisible = false;
            item.inputValue = "";
          });
          this.listData = res.data.data;
          this.form = {};
          this.dialogFormVisible = false;
        }
      }
    },
    editParams(row) {
      // console.log(row);
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogFormVisible = true;
    },
    addParams() {
      this.form.name = "";
      this.form.attr_id = "";
      this.form.cat_id = this.value[this.value.length - 1];
      this.form.attr_sel = this.activeName;
      this.dialogFormVisible = true;
    },
    async handleClick(tab) {
      tab.$options.propsData.name = this.activeName;
      if (this.value.length === 0) {
        return;
      }
      const res = await getGoodsAttribute({
        id: this.value[this.value.length - 1],
        sel: this.activeName,
      });
      res.data.data.forEach((item) => {
        // item.tag = {
        //   dynamicTags: ["标签一"],
        //   inputVisible: false,
        //   inputValue: "",
        // };
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (res.data.meta.status !== 200) {
        this.$message.error("获取参数列表失败");
        this.isBtnDisabled = true;
      } else {
        this.$message.success(res.data.meta.msg);
        this.isBtnDisabled = false;
      }
      this.listData = res.data.data;
    },
    async getCategoriesList() {
      const res = await getCategories();
      this.list = res.data.data;
      this.getOptions();
    },
    getOptions() {
      this.list.forEach((item) => {
        if (item.children) {
          this.options.push({
            value: item.cat_id,
            label: item.cat_name,
            children: item.children.map((item) => {
              if (item.children) {
                return {
                  value: item.cat_id,
                  label: item.cat_name,
                  children: item.children.map((item) => {
                    return {
                      value: item.cat_id,
                      label: item.cat_name,
                    };
                  }),
                };
              } else {
                return {
                  value: item.cat_id,
                  label: item.cat_name,
                };
              }
            }),
          });
        } else {
          this.options.push({
            value: item.cat_id,
            label: item.cat_name,
          });
        }
      });
      // console.log(this.options);
    },
    async handleChange(value) {
      this.value = value;
      const res = await getGoodsAttribute({
        id: this.value[this.value.length - 1],
        sel: this.activeName,
      });
      res.data.data.forEach((item) => {
        // item.tag = {
        //   dynamicTags: ["标签一"],
        //   inputVisible: false,
        //   inputValue: "",
        // };
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (res.data.meta.status !== 200) {
        this.$message.error("获取参数列表失败");
        this.isBtnDisabled = true;
      } else {
        this.$message.success(res.data.meta.msg);
        this.isBtnDisabled = false;
      }
      this.listData = res.data.data;
    },
    async handleClose(tag, row) {
      console.log(row.attr_vals.split(","));
      const arr = row.attr_vals.split(",");
      arr.splice(arr.indexOf(tag), 1);
      row.attr_vals = arr.join(",");
      const res = await addAttributes({
        cat_id: row.cat_id,
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_id: row.attr_id,
        attr_vals: row.attr_vals,
      });
      if (res.data.meta.status !== 200) {
        this.$message.error("设置失败");
      } 
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        // console.log(this.$refs.saveTagInput);
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleInputConfirm(row) {
      console.log(row.attr_vals)
      const res = await addAttributes({
        cat_id: row.cat_id,
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_id: row.attr_id,
        attr_vals: row.attr_vals+','+row.inputValue
      });
      if (res.data.meta.status !== 200) {
        this.$message.error("设置失败");
      } else {
        let inputValue = row.inputValue;
        if (inputValue) {
          const arr = [];
          arr.push(inputValue);
          const str = arr.join(",");
          if (row.attr_vals) {
            row.attr_vals += "," + str;
          } else {
            row.attr_vals += str;
          }
          // console.log(row.attr_vals);
        }
        row.inputVisible = false;
        row.inputValue = "";
      }
    },
  },
};
</script>
<style lang='less'  scoped>
main {
  width: 100%;
  background-color: #fff;
  margin-top: 15px;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 2px 2px 10px #ccc;
  .title {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
}
</style>
